package com.lagou.homework03;

import java.util.concurrent.locks.ReentrantLock;

public class TicketRunnableTest implements Runnable{
    private int ticketNumber;

    public TicketRunnableTest() { }
    public TicketRunnableTest(int ticketNumber) { this.ticketNumber = ticketNumber; }
    public int getTicketNumber() { return ticketNumber; }
    public void setTicketNumber(int ticketNumber) {
            this.ticketNumber = ticketNumber;
    }

    @Override
    public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "开始在卖票--");
            while (true) {
                //添加同步锁.因为对象只有一个account，所以可以实现锁机制
                synchronized (this) {
                    //唤醒阻塞状态的线程
                    notifyAll();
                    if (ticketNumber>0) {
                        ticketNumber -= 1;
                        try {
                            //等待0.1秒
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("线程" + Thread.currentThread().getName() + "出票一张，" + "请取走您的票");
                        System.out.println("剩余的票数为" + ticketNumber);
                        System.out.println("-----------------------------------------");
                        try {
                            //进入阻塞状态
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        break;
                    }
                }
            }

    }
    public static void main(String[] args) {

        TicketRunnableTest account = new TicketRunnableTest(100);

        Thread t1 = new Thread(account);
        Thread t2 = new Thread(account);
        Thread t3 = new Thread(account);

        t1.start();
        t2.start();
        t3.start();

        try {
                t1.join();
                t2.join();
                t3.join();
        } catch (InterruptedException e) {
                e.printStackTrace();
        }
        System.out.println("票卖完了");
    }

}
